package info.ask4research.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import info.ask4research.dao.IGraphDAO;
import info.ask4research.dao.core.impl.AbstractDaoImpl;
import info.ask4research.model.Graph;
import info.ask4research.model.addons.UploadingFiles;

@Repository("graphDAO")
public class GraphDAO extends AbstractDaoImpl<Graph> implements IGraphDAO{

	public GraphDAO() {
		super(Graph.class);
	}

	private HibernateTemplate hibernateTemplate;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
	
	@Override
	public List<Graph> getPaginated(int limit, int page, int start) {
		
		@SuppressWarnings("unchecked")
		List<Graph> graphs = hibernateTemplate.executeFind(new HibernateCallback() {  
			             public Object doInHibernate(Session session) throws HibernateException, SQLException {  
				                 Query query = (Query) session.createQuery("from Graph g");  
				                 query.setMaxResults(10);  
				                 query.setFirstResult(0);  
				                 return query.list();  
				             }  
				         }); 
		return graphs;
	}

	@Override
	public Graph getByHtmlCode(String htmlCode) {
		@SuppressWarnings("unchecked")
		List<Graph> graphs = (List<Graph>) hibernateTemplate.find("from Graph g where g.graphHtml=?",  htmlCode);
		if(graphs.isEmpty()){
			return null;
		}else{
			return graphs.get(0);
		}
	}

}
